package com.ruoyi.develop.goodsSaleMaterial.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.factory.factoryProduceSaleAll.domain.FactoryProduceSaleAll;
import com.ruoyi.develop.factory.factoryProduceSaleAll.service.IFactoryProduceSaleAllService;
import com.ruoyi.develop.goodsSaleMaterialChild.domain.GoodsSaleMaterialChild;
import com.ruoyi.develop.goodsSaleMaterialChild.service.IGoodsSaleMaterialChildService;
import com.ruoyi.develop.lvDo.domain.LvDo;
import com.ruoyi.develop.orderIronDetail.domain.OrderIronDetail;
import com.ruoyi.develop.orderIronDetail.service.IOrderIronDetailService;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsSaleMaterial.domain.GoodsSaleMaterial;
import com.ruoyi.develop.goodsSaleMaterial.service.IGoodsSaleMaterialService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 销售产品物料Controller
 *
 * @author qh
 * @date 2024-11-09
 */
@RestController
@RequestMapping("/goodsSaleMaterial/goodsSaleMaterial")
public class GoodsSaleMaterialController extends BaseController {
    @Autowired
    private IGoodsSaleMaterialService goodsSaleMaterialService;
    @Autowired
    private IOrderIronDetailService orderIronDetailService;
    @Autowired
    private IFactoryProduceSaleAllService iFactoryProduceSaleAllService;

    @Autowired
    private IGoodsSaleMaterialChildService goodsSaleMaterialChildService;
    /**
     * 查询销售产品物料列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsSaleMaterial entity) {
        startPage();
        List<GoodsSaleMaterial> list = goodsSaleMaterialService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 查询销售产品物料列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:query')")
    @GetMapping("/goodsSaleMaterialPleaseBuyList")
    public TableDataInfo goodsSaleMaterialPleaseBuyList(GoodsSaleMaterial entity) {
        startPage();
        List<GoodsSaleMaterial> list = goodsSaleMaterialService.goodsSaleMaterialPleaseBuyList(entity);
        return getDataTable(list);
    }


    /**
     * 导出销售产品物料列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:export')")
    @Log(title = "销售产品物料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsSaleMaterial entity) {
        List<GoodsSaleMaterial> list = goodsSaleMaterialService.selectList(entity);
        ExcelUtil<GoodsSaleMaterial> util = new ExcelUtil<GoodsSaleMaterial>(GoodsSaleMaterial.class);
        util.exportExcel(response, list, "销售产品物料数据");
    }

    /**
     * 获取销售产品物料详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsSaleMaterialService.selectById(id));
    }

    /**
     * 新增销售产品物料
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:add')")
    @Log(title = "销售产品物料", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsSaleMaterial entity) {
        return toAjax(goodsSaleMaterialService.insert(entity));
    }

    /**
     * 修改销售产品物料
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:edit')")
    @Log(title = "销售产品物料", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsSaleMaterial entity) {
        return toAjax(goodsSaleMaterialService.update(entity));
    }

    /**
     * 删除销售产品物料
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:remove')")
    @Log(title = "销售产品物料", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(goodsSaleMaterialService.deleteByIds(ids));
    }

    @DeleteMapping("/haveGoood/{ids}")
    public AjaxResult haveGoood(@PathVariable String[] ids) {
        return toAjax(goodsSaleMaterialService.deleteHaveGoood(ids));
    }

    @PostMapping("/insertForMaterial")
    public AjaxResult insertForMaterial(@Validated @RequestBody GoodsSaleMaterial entity) {
        FactoryProduceSaleAll factoryProduceSaleAll=iFactoryProduceSaleAllService.selectById(entity.getGsaleId());
        if(factoryProduceSaleAll!=null) {
            factoryProduceSaleAll.setChaijieDate(new Date());
            iFactoryProduceSaleAllService.update(factoryProduceSaleAll);
        }
        goodsSaleMaterialService.insertBatch(entity);
        return AjaxResult.success("选择完成！");
    }

    @PostMapping("/insertForMaterialPiliang")
    public AjaxResult insertForMaterialPiliang(@Validated @RequestBody GoodsSaleMaterial entity) {
        if((entity.getMainIds().length>0)){
            for(String mainId:entity.getMainIds()){
                FactoryProduceSaleAll factoryProduceSaleAll=iFactoryProduceSaleAllService.selectById(mainId);
                if(factoryProduceSaleAll!=null){
                    factoryProduceSaleAll.setChaijieDate(new Date());
                    iFactoryProduceSaleAllService.update(factoryProduceSaleAll);
                }
                entity.setGsaleId(mainId);
                goodsSaleMaterialService.insertBatch(entity);
            }
        }
        return AjaxResult.success("选择完成！");
    }
    /**
     * 新增销售产品物料
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsSaleMaterial:add')")
    @Log(title = "铁附件拆解物料", businessType = BusinessType.INSERT)
    @PostMapping("/addForIronList")
    public AjaxResult addForIronList(@Validated @RequestBody GoodsSaleMaterial entity) {
        // 先删除之前的list
        String ironDetailId = entity.getIronDetailId();
        if (StringUtils.isBlank(ironDetailId)) {
            return AjaxResult.error("请先选择铁附件！");
        }
        // 查询此次 拆解记录是否有同一个编码的
        OrderIronDetail orderIronDetail =  orderIronDetailService.selectById(ironDetailId);
        if(StringUtils.isNotBlank(orderIronDetail.getMaterialCode())){
            OrderIronDetail params = new OrderIronDetail();
            params.setRecordId(orderIronDetail.getRecordId());
            params.setMaterialCode(orderIronDetail.getMaterialCode());
            List<OrderIronDetail> list = orderIronDetailService.selectList(params);

            for(OrderIronDetail ironDetail:list){
                goodsSaleMaterialService.deleteByIronDetailId(ironDetailId);
                List<GoodsSaleMaterial> materialList = entity.getMaterialColumns();
                for (GoodsSaleMaterial material : materialList) {
                    if (StringUtils.isNotBlank(material.getGoodsId())) {
                        material.setIronDetailId(ironDetail.getId());
                        goodsSaleMaterialService.insert(material);
                    }
                }
                ironDetail.setIsBom(BusinessConstants.STATUS_YES);
                orderIronDetailService.update(ironDetail);
            }
        }else{
            goodsSaleMaterialService.deleteByIronDetailId(ironDetailId);
            List<GoodsSaleMaterial> materialList = entity.getMaterialColumns();
            for (GoodsSaleMaterial material : materialList) {
                if (StringUtils.isNotBlank(material.getGoodsId())) {
                    material.setIronDetailId(ironDetailId);
                    goodsSaleMaterialService.insert(material);
                }
            }
            orderIronDetail.setIsBom(BusinessConstants.STATUS_YES);
            orderIronDetailService.update(orderIronDetail);
        }
        return AjaxResult.success("保存成功！");
    }
    //一键应用拆解标准
    @DeleteMapping("/useGx/{ids}")
    public AjaxResult useGx(@PathVariable String[] ids) {
        return toAjax(goodsSaleMaterialService.useGxHaveGoood(ids));
    }

    @PostMapping("/addMaterial")
    public AjaxResult addMaterial(@RequestBody GoodsSaleMaterialChild entity) {
        List<GoodsSaleMaterial> materialList = entity.getGoodsSaleMaterial();
        for (GoodsSaleMaterial goodsSaleMaterial : materialList) {
            GoodsSaleMaterial goodsSaleMaterial1=goodsSaleMaterialService.selectById(goodsSaleMaterial.getId());
            GoodsSaleMaterialChild goodsSaleMaterialChild = new GoodsSaleMaterialChild();
            BeanUtils.copyProperties(goodsSaleMaterial1, goodsSaleMaterialChild, "id");
            goodsSaleMaterialChild.setGoodsCount(goodsSaleMaterial.getShengyuCount());
            goodsSaleMaterialChild.setLingquCount(BigDecimal.ZERO);
            goodsSaleMaterialChild.setShengyuCount(goodsSaleMaterial.getShengyuCount());
            goodsSaleMaterialChild.setMaterialdId(goodsSaleMaterial.getId());
            goodsSaleMaterialChild.setFactoryGoodssaleId(goodsSaleMaterial1.getProduceId());
            goodsSaleMaterialChild.setFactoryProdNo(goodsSaleMaterial1.getProduceNo());
            goodsSaleMaterialChild.setStatus(BusinessConstants.LINGLIAO_0);
            goodsSaleMaterialChildService.insert(goodsSaleMaterialChild);
            goodsSaleMaterial1.setLingquCount(goodsSaleMaterial1.getLingquCount().add(goodsSaleMaterial.getShengyuCount()));
            goodsSaleMaterial1.setShengyuCount(goodsSaleMaterial1.getShengyuCount().subtract(goodsSaleMaterial.getShengyuCount()));
            goodsSaleMaterialService.update(goodsSaleMaterial1);
        }
        return toAjax(1);
    }

    @PostMapping("/editMaterial")
    public AjaxResult editMaterial(@RequestBody GoodsSaleMaterialChild entity) {
        List<GoodsSaleMaterial> materialList = entity.getGoodsSaleMaterial();
        for (GoodsSaleMaterial goodsSaleMaterial : materialList) {
            GoodsSaleMaterial goodsSaleMaterial1=goodsSaleMaterialService.selectById(goodsSaleMaterial.getId());
            GoodsSaleMaterialChild goodsSaleMaterialChild = new GoodsSaleMaterialChild();
            BeanUtils.copyProperties(goodsSaleMaterial1, goodsSaleMaterialChild, "id");
            goodsSaleMaterialChild.setGoodsCount(goodsSaleMaterial.getShengyuCount());
            goodsSaleMaterialChild.setLingquCount(BigDecimal.ZERO);
            goodsSaleMaterialChild.setShengyuCount(goodsSaleMaterial.getShengyuCount());
            goodsSaleMaterialChild.setMaterialdId(goodsSaleMaterial.getId());
            goodsSaleMaterialChild.setFactoryGoodssaleId(goodsSaleMaterial1.getProduceId());
            goodsSaleMaterialChild.setFactoryProdNo(goodsSaleMaterial1.getProduceNo());
            goodsSaleMaterialChild.setStatus(BusinessConstants.LINGLIAO_1);
            goodsSaleMaterialChild.setParentId(entity.getParentId());
            goodsSaleMaterialChild.setLingliaoNo(entity.getLingliaoNo());
            goodsSaleMaterialChildService.insert(goodsSaleMaterialChild);
            goodsSaleMaterial1.setLingquCount(goodsSaleMaterial1.getLingquCount().add(goodsSaleMaterial.getShengyuCount()));
            goodsSaleMaterial1.setShengyuCount(goodsSaleMaterial1.getShengyuCount().subtract(goodsSaleMaterial.getShengyuCount()));
            //goodsSaleMaterial1.setStatus(BusinessConstants.LINGLIAO_1);
            goodsSaleMaterialService.update(goodsSaleMaterial1);
        }
        return toAjax(1);
    }

    // 删除物料单产品
    @DeleteMapping("/deleteMaterial/{ids}")
    public AjaxResult deleteMaterial(@PathVariable String[] ids) {
        return toAjax(goodsSaleMaterialService.deleteMaterial(ids));
    }

}
